package com.hibase.core.sequence.util;


import com.hibase.core.sequence.entity.MdsCodeSequence;
import com.hibase.core.sequence.service.MdsCodeSequenceRegexService;
import com.hibase.core.sequence.service.MdsCodeSequenceService;
import com.hibase.common.exception.HibaseAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 描述:
 * 单据号工具类
 *
 * @author li-wei-hua
 * @date 2020-09-11 15:21
 */
@Component
public class HibaseCodeSequenceUtil {



    @Autowired
    private MdsCodeSequenceService mdsCodeSequenceService;

    private static HibaseCodeSequenceUtil codeSequenceUtil;

    @Autowired
    private MdsCodeSequenceRegexService mdsCodeSequenceRegexService;

    @PostConstruct
    public void init() {
        codeSequenceUtil = this;
        codeSequenceUtil.mdsCodeSequenceService = this.mdsCodeSequenceService;
        codeSequenceUtil.mdsCodeSequenceRegexService = this.mdsCodeSequenceRegexService;
    }


    public static String generateCode(String sequenceType){
        // step 1. 根据序号规则生成单据号
        String code = codeSequenceUtil.mdsCodeSequenceRegexService.generateCode(sequenceType);
        // step 2. 返回单据号
        return code;
    }

    /**
     * 根据单据类型 以及 通配符 生成流水号
     * @param sequenceType
     * @param fix
     * @return
     */
    public static String generateCode(String sequenceType,String fix){
        // step 1. 根据序号规则生成单据号
        String code = codeSequenceUtil.mdsCodeSequenceRegexService.generateCode(sequenceType,fix);
        // step 2. 返回单据号
        return code;
    }

    /**
     * 根据单据Id
     * @param sequenceId
     * @return
     */
    public static String generateCodeById(String sequenceId){
        // step 1. 获取单据类型关联序号规则
        MdsCodeSequence codeSequence = codeSequenceUtil.mdsCodeSequenceService.getById(sequenceId);
        HibaseAssert.notNull(codeSequence,"单据类型不存在，请检查数据库配置");
        // step 2. 根据序号规则生成单据号
        String code = codeSequenceUtil.mdsCodeSequenceRegexService.generateCode(codeSequence.getSequenceType());
        // step 3. 返回单据号
        return code;
    }

    /**
     * 根据单据Id 以及前缀
     * @param sequenceId
     * @param fix
     * @return
     */
    public static String generateCodeById(String sequenceId,String fix){
        // step 1. 获取单据类型关联序号规则
        MdsCodeSequence codeSequence = codeSequenceUtil.mdsCodeSequenceService.getById(sequenceId);
        HibaseAssert.notNull(codeSequence,"单据类型不存在，请检查数据库配置");
        // step 2. 根据序号规则生成单据号
        String code = codeSequenceUtil.mdsCodeSequenceRegexService.generateCode(codeSequence.getSequenceType(),fix);
        // step 3. 返回单据号
        return code;
    }
}
